package com.sharemarking.application.wechat.controller;

import com.sharemarking.application.wechat.entity.Bless;
import com.sharemarking.application.wechat.repository.BlessRepo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/12.
 */
@Controller
@RequestMapping("bless")
public class BlessController {

    @Autowired
    BlessRepo blessRepo;

    /**
     * 祝福列表页
     * @param b
     * @param page
     * @param size
     * @param model
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    @PreAuthorize("hasPermission('w:bless', 1)")
    public void index(Bless b, Integer page, Integer size, Model model){
        if (page == null){
            page = 0;
        }else
            page -= 1;
        if (size == null){
            size = 10;
        }
        PageRequest req = new PageRequest(page, size);
        Page p = null;
        p = blessRepo.findAll(new Specification<Bless>() {
            @Override
            public Predicate toPredicate(Root<Bless> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (b.getFromClient() != null){
                    if (!StringUtils.isEmpty(b.getFromClient().getNickName())){
                        String fromClientName = b.getFromClient().getNickName();
                        predicates.add(cb.like(root.get("fromClient").get("name").as(String.class),
                                "%"+fromClientName));
                    }
                }
                predicates.add(cb.equal(root.get("delFlag").as(Boolean.class), false));
                return cb.and(predicates.toArray(new Predicate[] {}));
            }
        }, req);

        model.addAttribute("page", p);
        model.addAttribute("search", b);
    }
}
